package com.guapi.controller.interceptor;

import com.guapi.entity.Goods;
import com.guapi.entity.User;
import com.guapi.service.GoodsService;
import com.guapi.service.UserService;
import com.guapi.util.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

/**
 * 购物车属性，切换时有效
 */
@Component
public class GoodsCartInterceptor implements HandlerInterceptor {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;


    private static final Logger logger = LoggerFactory.getLogger(GoodsCartInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        long sumPrice = 0;
        if (user != null && modelAndView != null) {
            Set<Goods> goodsSet = goodsService.getCartGoods(user);
            ArrayList<HashMap<String, Object>> goodsSellerList = new ArrayList<>();
            if (goodsSet.size() != 0) {
                for (Goods goods : goodsSet) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("goods", goods);
                    map.put("userName", userService.findUserById(goods.getUserId()).getUserName());
                    sumPrice += goods.getPrice();
                    goodsSellerList.add(map);
                }
            }
            //modelAndView.addObject("goodsSet", goodsSet);
            modelAndView.addObject("goodsSellerList",goodsSellerList);
            modelAndView.addObject("setSize", goodsSet.size());
            modelAndView.addObject("sumPrice", sumPrice);

        }
    }
}
